package nuffzone;

import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class categoryServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		UserService userService = UserServiceFactory.getUserService();
		com.google.appengine.api.users.User user = userService.getCurrentUser();
		recipeManager RM = recipeManager.getInstance();
		categoriesManager CM = categoriesManager.getInstance();
		int result = 0;
		if (user == null) {
		} else {
				String name = req.getParameter("categoryName");
				String request = req.getParameter("request");
				if(request.equals("addCategory")){
					System.out.println("******ADD CATEGORY*****************");
					System.out.println("Creating category for user: " + user);
					System.out.println("name: " + name);
					result = CM.addCategoryForUser(user, name);
					System.out.println("-----------------------------------");
					System.out.println(" ");
				}
				else if(request.equals("removeCategory")){
					System.out.println("******REMOVE CATEGORY**************");
					System.out.println("Removing category for user: " + user);
					System.out.println("name: " + name);
					ArrayList<Recipe> recipeList = RM.getAllUserRecipesOfCategory(user, name);
					for(Recipe recipe: recipeList){
						RM.deleteRecipe(user, recipe.getTitle());
						System.out.println("--- removed recipe: "+recipe.getTitle());
					}
					result = CM.removeCategoryForUser(user, name);
					System.out.println("-----------------------------------");
					System.out.println(" ");
				}
		}
		if(result==1){
			resp.setStatus(200);
		}
		else if(result==-1){
			resp.setStatus(400);
		}
		else{
			resp.setStatus(404);
		}
		resp.sendRedirect("/recipes.jsp?page=manageCategories");
	}
}
